package com.yungu.swift.admin.route.marketing;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.yungu.swift.admin.utils.WorkbookUtil;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.model.admin.AdminUuidParam;
import com.yungu.swift.system.marketing.model.dto.MarketingChannelDto;
import com.yungu.swift.system.marketing.model.dto.MarketingChannelStatisticsDto;
import com.yungu.swift.system.marketing.model.dto.MarketingGiftDto;
import com.yungu.swift.system.marketing.model.param.AdminChannelStatisticsPageParam;
import com.yungu.swift.system.marketing.model.param.AdminCouponChannelParam;
import com.yungu.swift.system.marketing.model.param.AdminGiftUuidPageParam;
import com.yungu.swift.system.marketing.model.vo.MarketingChannelStatisticsExportVo;
import com.yungu.swift.system.marketing.service.MarketingChannelService;
import com.yungu.swift.system.marketing.service.MarketingChannelStatisticsService;
import com.yungu.swift.system.marketing.service.MarketingGiftService;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.ParamUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yungu.swift.admin.consts.AdminErrorEnum.PARAM_ERROR;

/**
 * @author : cuixiuyin
 * @date : 2019/8/7
 */
@RestController
@RequestMapping("/admin/v1/marketing/coupon/channel")
@Api(value = "【营销管理】", tags = "优惠券渠道管理")
public class CouponChannelAdmin {

    @Reference
    private MarketingGiftService marketingGiftService;
    @Reference
    private MarketingChannelService marketingChannelService;
    @Reference
    private MarketingChannelStatisticsService marketingChannelStatisticsService;

    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    @ApiOperation(value = "优惠券渠道分页查询", httpMethod = "POST")
    public ResponseData<PageVo<MarketingChannelDto>> queryPage(@RequestBody AdminGiftUuidPageParam giftUuidPageParam) {
        if (ParamUtil.isIllegal(giftUuidPageParam.getGiftUuid())) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        return marketingChannelService.queryPage(giftUuidPageParam);
    }


    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "优惠券渠道新增或更新", httpMethod = "POST")
    public ResponseData<Boolean> saveOrUpdate(@RequestBody AdminCouponChannelParam couponChannelParam) {
        if (ParamUtil.isIllegal(couponChannelParam.getGiftUuid())) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        return marketingChannelService.saveOrUpdate(couponChannelParam);
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ApiOperation(value = "优惠券渠道删除", httpMethod = "POST")
    public ResponseData<Boolean> remove(@RequestBody AdminUuidParam adminUuidParam) {
        if (ParamUtil.isIllegal(adminUuidParam.getUuid())) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        return marketingChannelService.del(adminUuidParam.getUuid(), MarketingChannelDto.class);
    }

    @RequestMapping(value = "/QrCode", method = RequestMethod.GET)
    @ApiOperation(value = "下载二维码", httpMethod = "GET")
    public void download(@RequestParam("uuid") String uuid, @RequestParam("giftUuid") String giftUuid, HttpServletResponse response) {
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>(4);
            hints.put(EncodeHintType.MARGIN, 0);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            MarketingGiftDto marketingGiftDto = marketingGiftService.get(giftUuid).getData();
            if (marketingGiftDto == null) {
                response.getWriter().print(JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(ResponseData.ERROR_CODE,
                        "获取不到礼包数据")));
            }
            MarketingChannelDto marketingChannelDto = marketingChannelService.get(uuid).getData();
            if (marketingChannelDto == null) {
                response.getWriter().print(JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(ResponseData.ERROR_CODE,
                        "获取不到渠道信息")));
            }
            String drawUrl = marketingChannelDto.getDrawUrl();
            BitMatrix bitMatrix = new QRCodeWriter().encode(drawUrl, BarcodeFormat.QR_CODE, 250, 250, hints);
            //1.去白边
            int[] rec = bitMatrix.getEnclosingRectangle();
            int resWidth = rec[2] + 1;
            int resHeight = rec[3] + 1;
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
            resMatrix.clear();
            for (int i = 0; i < resWidth; i++) {
                for (int j = 0; j < resHeight; j++) {
                    if (bitMatrix.get(i + rec[0], j + rec[1])) {
                        resMatrix.set(i, j);
                    }
                }
            }
            // 2
            int width = resMatrix.getWidth();
            int height = resMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, resMatrix.get(x, y) == true ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(marketingGiftDto.getName() + ".png", "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            ImageIO.write(image, "png", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/statistics", method = RequestMethod.POST)
    @ApiOperation(value = "优惠券渠道统计", httpMethod = "POST")
    public ResponseData<PageVo<MarketingChannelStatisticsDto>> statistics(@RequestBody AdminChannelStatisticsPageParam statisticsPageParam) {
        return marketingChannelStatisticsService.queryPage(statisticsPageParam);
    }

    @RequestMapping(value = "/statistics/export", method = RequestMethod.POST)
    @ApiOperation(value = "优惠券渠道统计导出", httpMethod = "POST")
    public void export(HttpServletResponse response, @RequestBody AdminChannelStatisticsPageParam statisticsPageParam) {
        try (OutputStream os = response.getOutputStream()) {
            List<MarketingChannelStatisticsExportVo> marketingChannelStatisticsExportVoList = marketingChannelStatisticsService.listExport(statisticsPageParam).getData();
            InputStream in = getClass().getResourceAsStream("/template/channelStatisticsTemplate.xlsx");
            Workbook workbook = new XSSFWorkbook(in);
            // 获取统计人数导入格式面板
            Sheet sheet = workbook.getSheetAt(0);
            WorkbookUtil.writeDataToExcelBySheet(sheet, marketingChannelStatisticsExportVoList, MarketingChannelStatisticsExportVo.class);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("channelStatistics.xlsx", "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            workbook.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
